package com.us.simple.common.context;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于线程绑定的请求上下文 , 异步场景限制, 子线程无法访问父线程的 ThreadLocal数据
 * <p>
 * 使用示例
 * RequestContextHolder.set("userId", "123");
 * RequestContextHolder.get("username");
 */
public class RequestContextHolder {
    private static final ThreadLocal<Map<String, Object>> contextHolder = ThreadLocal.withInitial(HashMap::new);

    public static void set(String key, Object value) {
        contextHolder.get().put(key, value);
    }

    public static <T> T get(String key) {
        return (T) contextHolder.get().get(key);
    }

    public static void clearContext() {
        contextHolder.remove();
    }
}
